<template>
  <!-- <div>采购</div> -->
  <VTable ref="tableRef" v-bind="tableOptins" class="is--card">
    <template #form="{ form }">
      <XForm :fieldList="fieldList" :formOption="{}" :formData="form">
        <template #create_user="{ value, input }">
          <VCascader
            :model-value="value"
            @update:model-value="input"
            collapse-tags
            class="w-[200px]"
            placeholder="请输入"
          />
        </template>
        <template #loanMonth="{ value, input }">
          <el-date-picker
            :model-value="value"
            @update:model-value="input"
            type="month"
            value-format="YYYY-MM"
            placeholder="货款所属月份"
          />
        </template>
      </XForm>
    </template>
    <template #toolbar_btns>
      <div class="w-full" v-if="totalData?.length">
        <el-tabs v-model="activeName" @tab-click="handleClick">
          <el-tab-pane
            :label="item.state.label"
            :name="item.state.value"
            v-for="(item, index) in totalData"
            :key="index"
          >
            <template #label>
              {{ item.state.label }}(<span
                :class="
                  activeName == item.state.value
                    ? 'base-text-color'
                    : 'text-[#999999]'
                "
                >{{ item.quantity }}</span
              >)
            </template>
          </el-tab-pane>
        </el-tabs>
      </div>
      <VActionBar :actions="actions"></VActionBar>
    </template>
    <template #operation="{ row }">
      <el-button
        v-hasPermi="[capitalAuthList.plan.fund_month.logistics.delete]"
        type="danger"
        link
        @click="handleDelete(row.id)"
      >
        删除
      </el-button>
      <!-- 日志 -->
      <el-button
        v-hasPermi="[capitalAuthList.plan.fund_month.logistics.log]"
        type="primary"
        link
        @click="handleLog(row)"
      >
        日志
      </el-button>
    </template>
  </VTable>
  <VAudit
    v-model="auditVisible"
    title="审核"
    :option="[
      { label: '待审核', value: 0 },
      { label: '已审核', value: 1 },
      { label: '审核失败', value: 2 },
    ]"
    url="/paymentScheduleLogistics/batch/review"
    :isRemark="false"
    method="patch"
    :ids="auditId"
    @close="auditId = null"
    @refresh="refresh"
  />
</template>
<script setup lang="jsx">
import { ElMessage } from "element-plus";
import XForm from "@/components/XForm/index.vue";
import { tabList } from "../../data.js";
import tagStatus from "@/components/tagStatus/index.vue";
import {
  getWeekPaymentScheduleLogistics,
  overviewPaymentScheduleLogistics,
  deletePaymentScheduleLogistics,
} from "../../api.js";
import { transformData } from "@/utils/tools.js";
import { getWeekRange } from "@/utils/time.js";
import { capitalAuthList } from "@/Auth/capital.js";
const { proxy } = getCurrentInstance();
const props = defineProps({
  optionsData: { type: Object, default: () => {} },
});
const { optionsData } = toRefs(props);
const totalData = ref([]);
const activeName = ref(0);
const tableRef = ref();
const getSum = async (params) => {
  const { data } = await overviewPaymentScheduleLogistics(params);
  const { stateQuantity, totalAmount } = data || {};
  let quantity = stateQuantity.reduce(
    (total, item) => total + item.quantity,
    0
  );
  let all = [{ state: { value: 0, label: "全部" }, quantity: quantity }];
  if (quantity == 0) {
    totalData.value = all;
  } else {
    let list = [...all, ...stateQuantity];
    totalData.value = list;
  }
};

let initWeek = getWeekRange();
const tableOptins = reactive({
  formConfig: {
    data: {
      dateRange: {
        type: "paymentTime",
        value: [initWeek[0].start, initWeek[4].end],
        range: false,
      },
    },
  },
  tooltipConfig: {
    showAll: false,
  },
  isToggle: true,
  columns: [
    {
      type: "checkbox",
      width: 50,
      fixed: "left",
    },
    {
      type: "sqe",
      title: "序号",
      width: 50,
      fixed: "left",
    },
    {
      title: "费用类型",
      field: "todo",
      minWidth: 100,
    },
    {
      title: "物流商",
      field: "providerName",
      minWidth: 100,
    },
    {
      title: "经办人",
      field: "handlerUser",
      minWidth: 100,
    },
    {
      title: "状态",
      slots: {
        default: ({ row }) => {
          return (
            <tagStatus
              code={row?.state}
              type={[
                { label: 1, value: "warning" },
                { label: 2, value: "primary" },
                { label: 3, value: "danger" },
              ]}
            />
          );
        },
      },
      minWidth: 100,
    },
    {
      title: "账期类型",
      field: "type",
      minWidth: 100,
    },
    {
      title: "货款所属月份",
      field: "monthPeriod",
      minWidth: 100,
    },
    {
      title: "贷款到期日",
      field: "expiringDate",
      minWidth: 100,
    },
    {
      title: "币种",
      field: "currency",
      minWidth: 100,
    },
    {
      title: "货款总额",
      field: "loanAmount",
      minWidth: 100,
    },
    {
      title: "实时汇率",
      field: "exchangeRate",
      minWidth: 100,
    },
    {
      title: "本期付款人民币金额",
      field: "localAmount",
      minWidth: 100,
    },
    {
      title: "付款时间",
      field: "paymentTime",
      minWidth: 100,
    },
    {
      title: "付款主体",
      field: "accountPrincipal",
      minWidth: 100,
    },
    {
      title: "付款类型",
      field: "paymentType",
      minWidth: 100,
      slots: {
        default: ({ row }) => {
          return <div>{row?.paymentType?.label}</div>;
        },
      },
    },
    {
      title: "备注",
      field: "remark",
      minWidth: 100,
    },
    {
      title: "添加时间",
      field: "createdAt",
      minWidth: 100,
    },
    {
      title: "添加人",
      field: "createUser",
      minWidth: 100,
    },
    {
      width: 160,
      title: "操作",
      fixed: "right",
      slots: { default: "operation" },
    },
  ],
  proxyConfig: {
    props: {
      result: "data",
      total: "total",
    },
    autoLoad: false,
    ajax: {
      query: ({ page, form }) => {
        let params = transformData(form);
        params.periodType = "month";
        if (params?.paymentTimeStart) {
          const timePay = getWeekRange(params.paymentTimeStart);
          params.paymentTimeStart = timePay[0].start;
          params.paymentTimeEnd = timePay[4].end;
        }
        if (params?.createdAtStart) {
          params.createdAtStart = `${params.createdAtStart} 00:00:00`;
          params.createdAtEnd = `${params.createdAtEnd} 23:59:59`;
        }
        getSum(params);
        return getWeekPaymentScheduleLogistics({ ...params, ...page }).then(
          (res) => {
            return {
              data: res.data,
              total: res.total,
            };
          }
        );
      },
    },
  },
});

const handleDelete = (id) => {
  proxy?.confirm({
    title: "提示",
    content: (
      <p>
        确认删除
        <span class="text-[#3366F1] px-[4px]">{1}</span>
        条数据？
      </p>
    ),
    beforeClose: async (action, instance, done) => {
      if (action === "confirm") {
        try {
          instance.confirmButtonLoading = true;
          instance.confirmButtonText = "处理中..";
          const { code, message } = await deletePaymentScheduleLogistics({
            id,
          });
          if (code !== 200) return ElMessage.success(message);
          ElMessage.success("删除成功!");
        } catch (e) {
          console.error(e);
        } finally {
          instance.confirmButtonLoading = false;
          done();
          refresh();
        }
      } else {
        done();
      }
    },
  });
};
const handleLog = (val) => {};
const refresh = () => {
  tableRef?.value.$table.commitProxy("query");
};
const publicStyle = { style: { width: "240px" } };
const fieldList = [
  {
    field: "logisticsCostItems",
    originOption: "logistics_cost",
    type: "select",
    multiple: true,
    options: {
      placeholder: "费用类型",
    },
    style: { width: "240px" },
  },
  {
    field: "providerIds",
    originOption: "providerName",
    type: "select",
    multiple: true,
    options: {
      placeholder: "物流商",
    },
    style: { width: "240px" },
  },
  {
    field: "type",
    type: "input",
    placeholder: "账期类型",
    style: { width: "150px" },
  },
  {
    field: "loanMonth",
    placeholder: "贷款所属月份",
    style: { width: "150px" },
    slot: "loanMonth",
  },
  {
    field: "principalIds",
    type: "select",
    multiple: true,
    options: {
      placeholder: "付款主体",
    },
    style: { width: "240px" },
  },
  {
    field: "user",
    selectStyle: { width: "120px" },
    select: [
      { label: "采购人", value: "handlerUsers" },
      { label: "添加人", value: "createUsers" },
    ],
    slot: "create_user",
  },
  {
    field: "dateRange",
    type: "daterange",
    style: { width: "360px" },
    select: [
      { label: "付款时间", value: "paymentTime" },
      { label: "货款到期时间", value: "expiringDate" },
      { label: "添加时间", value: "createdAt" },
    ],
    selectStyle: { width: "120px" },
    itemProps: {
      startPlaceholder: "创建最早时间",
      endPlaceholder: "创建最晚时间",
    },
  },
  {
    field: "paymentType",
    type: "select",
    originOption: "payment_type",
    options: {
      placeholder: "付款类型",
    },
    style: { width: "150px" },
  },
];
//审核
const auditVisible = ref(false);
const auditId = ref(null);
const handleAudit = () => {
  let records = tableRef.value?.$table.getCheckboxRecords();
  if (!records?.length) return ElMessage.warning("请至少选择一条数据!");
  const ids = records.map((item) => item.id);
  auditId.value = ids;
  auditVisible.value = true;
};
const handleImport = () => {};
const handleExport = () => {};
const actions = [
  {
    label: "审核",
    type: "primary",
    fn: handleAudit,
    permission: [capitalAuthList.plan.fund_month.logistics.audit],
  },
  {
    label: "导入",
    right: true,
    dkicon: "icon-Download",
    fn: handleImport,
    permission: [capitalAuthList.plan.fund_month.logistics.import],
  },
  {
    label: "导出",
    right: true,
    dkicon: "icon-Upload",
    fn: handleExport,
    permission: [capitalAuthList.plan.fund_month.logistics.export],
  },
];
</script>
<style lang="scss" scoped>
.vx-table {
  height: calc(100% - 40px) !important;
}
</style>
